package com.sky.websocket;

import com.sky.config.WebSocketConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * socket 服务器
 *
 * @author normal
 * @date 2025年03月04日 下午7:35
 */
@Slf4j
@ServerEndpoint(value = "/ws/{sid}")
@Component
public class WebSocketServer {

    // 存储会话记录
    private static final Map<String, Session> sessionMap = new HashMap<String, Session>();

    /**
     * 客户端建立socket连接
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        log.info("客户端:{} 建立连接",sid);
        sessionMap.put(sid, session);
    }

    /**
     *  客户端断开socket连接
     */
    @OnClose
    public void onClose(Session session, @PathParam("sid") String sid) {
        log.info("客户端:{} 断开连接", sid);
        sessionMap.remove(sid);
    }

    /**
     * 收到客户端消息调用方法
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到客户端[{}]发送的消息:", message);
    }

    public void sendMessageToAll(String message) {
        Collection<Session> values = sessionMap.values();
        for (Session session : values) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                log.error("群体发送消息异常");
                throw new RuntimeException(e);
            }
        }
    }

    @OnError
    public void onError(Throwable throwable, Session session) {
        // 获取session中路径参数{sid}
        String sid = session.getPathParameters().get("sid");
        log.error("连接[{}]失败,{}", sid, throwable.getMessage(),throwable);
    }

}
